-- gather_suit
-- Created by chengb Sep/11/2015
-- 成就：收集套装

-- 内部函数声明
local whenSuitActive;

-- 注册套装激活的回调
EventMgr.register("game_achievement/gather_suit", event.SUIT_ACTIVE, function(args)
    whenSuitActive(args);
end);

-- 注册套装激活的回调
whenSuitActive = function(args)
    -- 获取已经激活的套装记录
    local activeSuits = ME.user.dbase:query("active_suits", {});
    
    -- 判断是否是符合要求的成就
    local function isValidId(id)
        if true == GameAchievementM.isCompleted(id) then
            -- 已经完成了
            return false;
        end

        local config = GameAchievementM.query(id);
        local ruleArg = config["rule_arg"];
        
        -- 统计已收齐的数量
        local count = 0;
        if type(ruleArg) == 'table' and type(ruleArg["suits"]) == 'table' then
            for _, suitId in pairs(ruleArg["suits"]) do
                if table.indexOf(activeSuits, suitId) ~= -1 then
                    count = count + 1;
                end
            end
        end
        
        local requireNum = ruleArg["require_num"];
        if count < requireNum then
            -- 还有套装没收齐
            return false;
        end

        return true;
    end

    -- 遍历所有的子规则
    local ids = GameAchievementM.getIdsByRule("gather_suit");
    for _, id in pairs(ids) do
        if isValidId(id) then
            -- 尝试完成成就
            GameAchievementM.tryComplete(id, 1);
        end
    end
end

return {
    -- 获取成就描述
    queryDesc = function(id)
        local config = GameAchievementM.query(id);
        local desc = config["desc"];
        local ruleArg = config["rule_arg"];
        local suits = ruleArg["suits"];
        
        local activeCount = 0;
        local totalCount = ruleArg["require_num"];
        local activeSuits = ME.user.dbase:query("active_suits", {});
        for i, suitId in pairs(ruleArg["suits"]) do
            
            -- 统计已收齐的数量
            if table.indexOf(activeSuits, suitId) ~= -1 then
                activeCount = activeCount + 1;
            end
        end
        
        desc = string.gsub(desc, "{require_num}", totalCount);
        
        -- 加上进度
        desc = desc .. "\n" .. string.format(getLocStr("achievement_progress"), activeCount, totalCount);
        return desc;
    end,
};